#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <debug_printf.h>
#include "PahoMqttClient.h"
#include "thmar_types.h"
#include "local_error.h"
#include "sds.h"

#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientSub"
#define TOPIC       "test_paho"
#define USERNAME    "user"
#define PASSWORD    "password"
#define PAYLOAD     "Hello World!"

using namespace smq;
ThmarMqttClient* client;
// 定义在程序退出时执行的函数
void cleanup() {
    printf("Program exiting, cleaning up...\n");
    if(client)
    {
        printf("Stopping client...\n");
        client->stop();
        delete client;
        client = NULL;
    }
}
// 自定义的信号处理函数
void handle_sigint(int sig) {
    printf("Catch Ctrl-C, exit program.\n");
    exit(0);
}
// 打印 mqtt 消息负载, 仅用于调试
// payload指针指向的消息负载不一定是以null结尾的, 所以不能用printf打印
// 需要使用sds加'\0'的方式打印,sds分配的内存在打印后释放
static void print_playload(const char *payload, int payloadlen)
{
    if (payload && payloadlen > 0)
    {
        sds s = sdsnewlen(payload, payloadlen);
        printf("payload: %s\n", s);
        sdsfree(s);
    }
}
// 消息回调函数
void messageCallback(void *context, const char *message, size_t length)
{
    printf("Received message:\n");
    print_playload(message, length);
}
int main(int argc, char* argv[])
{
    // dbg_set_debuglog(true);
    // 注册退出时执行的函数
    if (atexit(cleanup) != 0) {
        fprintf(stderr,"failed to register cleanup function, exiting...\n");
        exit(1);
    }
    // 设置信号处理器
    signal(SIGINT, handle_sigint);

    client = new PahoMqttClient(ADDRESS, USERNAME, PASSWORD,CLIENTID);
    printf("PahoMqttClient created\n");
    printf("Connecting to server...\n");
    int code = client->start();
    if(code){
        printf("Connect failed with code %d\n", code);
        thmar_print_local_err();
        exit(1);
    }else{
        printf("Connect success\n");
    }
    printf("Subscribing to topic '%s' for client '%s'\n",TOPIC, CLIENTID);
    code = client->registerChannel(TOPIC, nullptr, messageCallback);
    if(code){
        printf("Subscribe failed with code %d\n", code);
        thmar_print_local_err();
    }else{
        printf("Press Q<Enter> to quit\n\n");
        int ch;
        do
        {
            ch = getchar();
        } while (ch!='Q' && ch != 'q');
    }
    return 0;
}



